package com.xhs.common.error;

import com.xhs.common.enums.XhsType;
import com.xhs.common.util.json.XhsGsonBuilder;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 错误码
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class XhsError implements Serializable {
  private static final long serialVersionUID = 7869786563361406291L;

  /**
   * 微信错误代码.
   */
  private int code;

  /**
   * 微信错误信息.
   * （如果可以翻译为中文，就为中文）
   */
  private String msg;

  /**
   * 微信接口返回的错误原始信息（英文）.
   */
  private Boolean success;

  private String data;

  private String json;

  public XhsError(int errorCode, String errorMsg) {
    this.code = errorCode;
    this.msg = errorMsg;
  }

  public static XhsError fromJson(String json) {
    return fromJson(json, null);
  }

  public static XhsError fromJson(String json, XhsType type) {
    final XhsError wxError = XhsGsonBuilder.create().fromJson(json, XhsError.class);
    if (wxError.getCode() == 0 || type == null) {
      return wxError;
    }

    switch (type) {
      case MiniApp: {
        final String msg = XhsMaErrorMsgEnum.findMsgByCode(wxError.getCode());
        if (msg != null) {
          wxError.setMsg(msg);
        }
        break;
      }
      case Open: {
        final String msg = XhsOpenErrorMsgEnum.findMsgByCode(wxError.getCode());
        if (msg != null) {
          wxError.setMsg(msg);
        }
        break;
      }
      default:
        return wxError;
    }

    return wxError;
  }

  @Override
  public String toString() {
    if (this.json == null) {
      return "错误代码：" + this.code + ", 错误信息：" + this.msg;
    }

    return "错误代码：" + this.code + ", 错误信息：" + this.msg + "，小红书原始报文：" + this.json;
  }

}
